package com.dailyblue.example.springcloud.consumer.basic.service.impl;

import com.dailyblue.example.springcloud.commons.util.JsonResult;
import com.dailyblue.example.springcloud.consumer.basic.service.ConsumerBasicService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class ConsumerBasicServiceImpl implements ConsumerBasicService {
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private DiscoveryClient discoveryClient;

    @Override
    public JsonResult a() {
        log.info("开始访问业务层的a方法");
        // 就会获取到所有cloud-example-provider名称实例
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-example-provider");
        // 假设目前只有一个
        ServiceInstance instance = instances.get(0);
        // 获取路径 http://localhost:8011/
        String uri = instance.getUri().toString();
        // 获取完成路径
        String url = uri + "/provider/a";
        log.info("实例的路径是：{}", url);
        return restTemplate.getForObject(url, JsonResult.class);
    }

    private int index = 0;

    @Override
    public JsonResult b() {
        // 就会获取到所有cloud-example-provider名称实例
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-example-provider");
        // 按照轮询的方式进行负载均衡
        ServiceInstance instance = instances.get(index);
        if (index == instances.size() - 1) {
            index = 0;
        } else {
            index++;
        }
        // 获取路径 http://localhost:8011/
        String uri = instance.getUri().toString();
        // 获取完成路径
        String url = uri + "/provider/a";
        log.info("实例的路径是：{}", url);
        return restTemplate.getForObject(url, JsonResult.class);
    }

    public JsonResult c() {
        // 就会获取到所有cloud-example-provider名称实例
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-example-provider");
        // 按照随机的方式进行负载均衡
        int num = (int) (Math.random() * instances.size());
        ServiceInstance instance = instances.get(num);
        // 获取路径 http://localhost:8011/
        String uri = instance.getUri().toString();
        // 获取完成路径
        String url = uri + "/provider/a";
        log.info("实例的路径是：{}", url);
        return restTemplate.getForObject(url, JsonResult.class);
    }
}
